package com.shoujifeng.snowmusic.player;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.ListView.XListView;
import com.shoujifeng.snowmusic.ListView.XListViewFooter;
import com.shoujifeng.snowmusic.ListView.XListView.IXListViewListener;
import com.shoujifeng.snowmusic.adapter.LoaderAdapter;
import com.shoujifeng.snowmusic.adapter.OnlineListAdapter;
import com.shoujifeng.snowmusic.adapter.adapt;
import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.interfaces.MoreInterface;
import com.shoujifeng.snowmusic.player.utils.LoadMask;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;

/**
 * 专辑详情列表
 * @author Administrator
 *
 */
public class OnlineSpecialContentActivity extends Activity implements IXListViewListener{
	private XListView listView;
	private OnlineListAdapter mAdapter;
	private RelativeLayout headView;
	private TextView headText;
	private View lineLay;
	private ImageButton breakBtn;
	private final int UPDATE_DATA = 0;
	private ServerAccess serverAccess;
	private ArrayList<HashMap<String, Object>> mTmpList;
	private ArrayList<HashMap<String, Object>> mMusicList;
	private Thread accThread;
	private Handler mHandler;
	private int mPage =  0;
	private LoadMask mLoadMask;

	//收藏
		private boolean bHave;
		private int index;
		
		//数据库操作
		DatabaseUtil mDb;
		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.online_special_content);
		init();
		initGlobalValue();
		setListView();
		mLoadMask = new LoadMask(this);
		mLoadMask.startLoad();
		XListViewFooter.mContentView.setVisibility(View.GONE);
		accThread = new Thread(runnable);
		accThread.start();
		
		mDb = new DatabaseUtil(this);
	}

	public void init() {
		mHandler = new Handler();
		serverAccess = new ServerAccess(OnlineSpecialContentActivity.this);
		listView = (XListView) findViewById(R.id.my_collect_single_list);
		listView.setPullLoadEnable(true);
		listView.setXListViewListener(this);
		headView = (RelativeLayout) findViewById(R.id.headLay);
		headText = (TextView) headView.findViewById(R.id.head_text);
		headText.setText(getIntent().getExtras().getString(ServerAccess.ALBUM).toString());
		breakBtn = (ImageButton) headView.findViewById(R.id.breakBtn);
		breakBtn.setOnClickListener(onClickListener);
		listView.setDivider(null);
		lineLay = LayoutInflater.from(OnlineSpecialContentActivity.this).inflate(R.layout.line_layout, null);
		listView.addFooterView(lineLay);
		
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(OnlineSpecialContentActivity.this, MusicPlayerActivity.class);
				MusicPlayerActivity.mOlineMusicList = mMusicList;
				MusicPlayer.position = arg2;
				 MusicPlayer.MUSCI_MSG =1;
				MusicPlayerActivity.isOnline = true ;
				startActivity(intent);
				

				overridePendingTransition(R.anim.bottom_in,android.R.anim.fade_out);
			}
		});
	}
	private View.OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {

			case R.id.breakBtn:
				 finish();
				 overridePendingTransition(R.anim.no_move, R.anim.right_out);
				break;
			default:
				break;
			}
			
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
		{
			finish();
			
			overridePendingTransition(R.anim.no_move, R.anim.right_out);
		}
			break;

		default:
			break;
		}
		
		return super.onKeyDown(keyCode, event);
	}

	//online_special_content_list
	private void setListView() {
		mMusicList = new ArrayList<HashMap<String, Object>>();
		String keys[] = new String[] { ServerAccess.MUSIC_NAME,ServerAccess.SINGER };
		mAdapter = new OnlineListAdapter(this, mMusicList, new int[] {
				R.id.musicName, R.id.playerName }, keys,
				new String[] { ServerAccess.ICON_URL },
				new int[] { R.id.face }, R.drawable.icon_music_default,
				R.layout.online_special_content_list);
		mAdapter.addInterfaceOnMore(mMoreInterface);
		listView.setAdapter(mAdapter);
	}
	//添加List回调事件
		private MoreInterface mMoreInterface = new MoreInterface() {
			
			@Override
			public void OnClickDownload(int position) {
				HashMap<String, Object> map = mMusicList.get(position);
				GlobalValue.g_DownloadManager.addDownload(map);
				
				Toast.makeText(OnlineSpecialContentActivity.this, "已加入下载!", Toast.LENGTH_LONG).show();
			}

			@Override
			public void OnClickConllect(int position, Boolean have) {

				if(ServerAccess.uid > 0) {
					
					HashMap<String, Object> map = mMusicList.get(position);
					int index = Integer.parseInt(map.get(ServerAccess.INDEX).toString());
					
					OnlineSpecialContentActivity.this.index = index;
					
					bHave = have;
					if(!have) {
						//写入本地
						mDb.insertConllect(index, ServerAccess.uid);
						
						//写入网络
						Thread thread = new Thread(delRunnable);
						thread.start();
						
						//收藏成功
						Toast.makeText(OnlineSpecialContentActivity.this, "收藏成功!", Toast.LENGTH_LONG).show();
					}
					else {
						mDb.deleteConllect(index);
						
						//写入网络
						Thread thread = new Thread(delRunnable);
						thread.start();
						
						Toast.makeText(OnlineSpecialContentActivity.this, "已删除收藏!", Toast.LENGTH_LONG).show();
					}
					
					
				}
				else {
					//跳登陆
					Intent intent = new Intent(OnlineSpecialContentActivity.this,
							LoginActivity.class);
					startActivity(intent);
					
					overridePendingTransition(R.anim.right_in, R.anim.left_out);
				}
			}
		};
		
		//删除收藏
		//BY Kress
		protected Runnable delRunnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					if(bHave) {
						serverAccess.delToConllect(index, ServerAccess.uid, new String[]{});
					}
					else {
						serverAccess.addToConllect(index, ServerAccess.uid, new String[]{});
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		};
	
	private void initGlobalValue() {
		GlobalValue.initSDAddr();

		GlobalValue.addUrl(ServerAccess.ALBUM_MUSIC_LIST,
				"http://www.snowmusic.com.cn/mobile_api/album_music_list.php");
	}

	protected Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case UPDATE_DATA: {
				mLoadMask.stopLoad();
				XListViewFooter.mContentView.setVisibility(View.VISIBLE);
				updateArrayList();
			}
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	// 创建多线程获取数据
	protected Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				String[] keys = new String[] { ServerAccess.MUSIC_NAME,
						ServerAccess.SINGER, ServerAccess.INDEX,
						ServerAccess.MUSIC_FILE ,ServerAccess.ICON_URL,ServerAccess.ALBUM,ServerAccess.LAN,ServerAccess.CODE};
				mTmpList = new ArrayList<HashMap<String, Object>>();
				String index = getIntent().getExtras().getString(ServerAccess.INDEX).toString();
				String singer = getIntent().getExtras().getString(ServerAccess.SINGER).toString();
				String album = getIntent().getExtras().getString(ServerAccess.ALBUM).toString();
				mTmpList = serverAccess.getAlbumMusicList(keys,index,singer,mPage,album);
				sendMessage(UPDATE_DATA);

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	};

	// 发送消息到Handler
	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	// 若在线程中更新与Adapter的动态数组将会产生致命错误。
	private void updateArrayList() {

		if (mMusicList != null) {
			int count = mTmpList.size();
			for (int i = 0; i < count; i++) {
				mMusicList.add(mTmpList.get(i));
			}

			 mTmpList.clear();
			 mTmpList = null;
		}

		mAdapter.notifyDataSetChanged();
	}
	
	private void onLoad() {
		listView.stopRefresh();
		listView.stopLoadMore();
		listView.setRefreshTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	}

//	@Override
//	public void onRefresh() {
//		// TODO Auto-generated method stub
//		mHandler.postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				onLoad();
//			}
//		}, 1);
//	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				mPage = mPage+1;
				accThread = new Thread(runnable);
				accThread.start();
				onLoad();
			}
		}, 1000);
		
	}
}
